<?php

/**
 * 兑换
 * Class mall
 */
class mall {

    private $_auth;
    private $db_content;
    private $db_mall;

    public function  __construct() {
        $this->_auth = param::get_cookie('auth');
        $this->db_content = pc_base::load_model('content_model');
        $this->db_mall = pc_base::load_model('mall_model');

        if (!$this->_auth) {
            json_exit('请先登录', 201);
        }
    }

    //兑换
    public function buy() {
        $uid = (int)param::get_cookie('_userid');
        $a_catid = $_POST['catid'] ? (int)$_POST['catid'] : 0;
        $a_id = $_POST['id'] ? (int)$_POST['id'] : 0;
        $jifen = $_POST['jifen'] ? (int)$_POST['jifen'] : 0;
        $realname = $_POST['realname'] ? $_POST['realname'] : '';
        $mobile = $_POST['mobile'] ? $_POST['mobile'] : '';
        $city = $_POST['city'] ? (int)$_POST['city'] : '';
        $address = $_POST['address'] ? $_POST['address'] : '';

        if (!$a_catid || !$a_id || !$realname || !$mobile || !$city || !$address) {
            json_exit('null', 300, '信息不完整');
        }

        $db_member = pc_base::load_model('member_model');
        $user_info = $db_member->get_one(['userid' => $uid]);
        if ($user_info['exp'] < 200) {
            json_exit('null', 300, '经验到达200(2级) 才能进行兑换');
        }

        //
        $CATEGORYS = getcache('category_content_1', 'commons');
        $modelid = $CATEGORYS[$a_catid]['modelid'];
        $db_content = pc_base::load_model('content_model');
        $db_content->set_model($modelid);
        $good_info = $db_content->get_one(['id' => $a_id]);
        if (!$good_info) {
            json_exit('null', 300, '课程不存在');
        }

        $good_price = (int)$jifen;

        $is_hasbuy = $this->db_mall->count(['uid' => $uid, 'a_catid' => $a_catid, 'a_id' => $a_id]);
        if ($is_hasbuy) {
            json_exit('null', 300, '您已经购买过了');
        }

        //扣分
        $cha = $db_member::log($uid, -1 * $good_price, $db_member::TYPE_SHOP, '购买' . $good_info['title'], __METHOD__);
        if ($cha) {
            json_exit('null', 300, "积分不足,还需$cha");
        }

        //记录订单
        $res = $this->db_mall->insert([
            'uid' => $uid,
            'a_catid' => $a_catid,
            'a_id' => $a_id,
            'cost' => $good_price,
            'realname' => $realname,
            'mobile' => $mobile,
            'city' => $city,
            'address' => $address,
            'ip' => ip(),
            'ymd' => date('Y-m-d'),
            'ymdhis' => date('Y-m-d H:i:s'),
        ]);

        json_exit('null', 100, '购买成功');
    }

}